# Maintainer: Martell Malone <martellmalone@gmail.com>
# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Ray Donnelly <mingw.android@gmail.com>
# Contributor: Mateusz Mikuła <mati865@gmail.com>
# Contributor: wirx6 <wirx654@gmail.com>
# Contributor: Yuui Tanabe <yuuitanabe@163.com>
# Contributor: Oscar Fuentes <ofv@wanadoo.es>
# Contributor: Adrian Pop <adrian.pop@liu.se>

if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
  _clangprefix=1
  _compiler=clang
else
  _compiler=clang
fi
_realname=clang
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-clang-analyzer"
         "${MINGW_PACKAGE_PREFIX}-clang-tools-extra"
         "${MINGW_PACKAGE_PREFIX}-compiler-rt"
         $( (( _clangprefix )) && echo "${MINGW_PACKAGE_PREFIX}-gcc-compat" )
         "${MINGW_PACKAGE_PREFIX}-lld"
         "${MINGW_PACKAGE_PREFIX}-llvm"
         "${MINGW_PACKAGE_PREFIX}-llvm-libs")
_version=16.0.5
_rc=""
_tag=llvmorg-${_version}${_rc}
pkgver=${_version}${_rc/-/}
pkgrel=3
pkgdesc="C language family frontend for LLVM (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://llvm.org/"
license=("custom:Apache 2.0 with LLVM Exception")
groups=($( (( _clangprefix )) && echo "${MINGW_PACKAGE_PREFIX}-toolchain"))
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-z3"
             "${MINGW_PACKAGE_PREFIX}-libffi"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-pkg-config"
             "${MINGW_PACKAGE_PREFIX}-python-sphinx"
             "${MINGW_PACKAGE_PREFIX}-python"
             "${MINGW_PACKAGE_PREFIX}-libunwind"
             $([[ "$_compiler" == "clang" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-clang" || echo \
               "${MINGW_PACKAGE_PREFIX}-gcc")
             $((( _clangprefix )) && echo \
               "${MINGW_PACKAGE_PREFIX}-compiler-rt" \
               "${MINGW_PACKAGE_PREFIX}-libc++")
             "git"
             )
_url=https://github.com/llvm/llvm-project/releases/download/${_tag}
source=("${_url}/llvm-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/clang-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/clang-tools-extra-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/compiler-rt-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/lld-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/cmake-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/third-party-${pkgver}.src.tar.xz"{,.sig}
        "0001-Fix-GetHostTriple-for-mingw-w64-in-msys.patch"
        "0002-Revert-CMake-try-creating-symlink-first-on-windows.patch"
        "0003-add-pthread-as-system-lib-for-mingw.patch"
        "0004-enable-emutls-for-mingw.patch"
        "0005-Fix-Any-linker-error-with-multiple-compilers.patch"
        "0006-COFF-Remove-misleading-and-unclear-comments.-NFC.patch"
        "0007-llvm-dlltool-Clarify-parameters-simplify-ArgList-usa.patch"
        "0008-llvm-dlltool-Ignore-the-temp-prefix-option.patch"
        "0009-llvm-dlltool-Implement-the-no-leading-underscore-opt.patch"
        "0101-link-pthread-with-mingw.patch"
        "0102-Rename-flang-new-flang-experimental-exec-to-flang.patch"
        "0303-ignore-new-bfd-options.patch"
        "https://github.com/llvm/llvm-project/commit/ab8d4f5a122fde5740f8c084c8165f51a26c93c7.patch")
# Some patch notes :)
#0001-0099 -> llvm
#0101-0199 -> clang
#0201-0299 -> rt
#0301-0399 -> lld
#0401-0499 -> clang-tools-extra
sha256sums=('701b764a182d8ea8fb017b6b5f7f5f1272a29f17c339b838f48de894ffdd4f91'
            'SKIP'
            'f4bb3456c415f01e929d96983b851c49d02b595bf4f99edbbfc55626437775a7'
            'SKIP'
            '63323e37dac6f7425c6defb1d7f06b830b024223c4a4106df3bbb16602b20f2f'
            'SKIP'
            '2a5c212e7eb2de78b8c54d1f3d474bfc6330447c3a40944899f3607d0cc91995'
            'SKIP'
            '0c593d1c23f626dc33caa8bf112868f77126e018b58dd1641f5ae6aa1c2a0ce3'
            'SKIP'
            '9400d49acd53a4b8f310de60554a891436db5a19f6f227f99f0de13e4afaaaff'
            'SKIP'
            '0a4bbb8505e95570e529d6b3d5176e93beb3260f061de9001e320d57b59aed59'
            'SKIP'
            'eb03df53671df6627768141b3aaa76abe176a14e5e47911c97bec544387c4aff'
            '5754c357cfc17769e80d95b673d41b1e54616e2487e037d761a1ac8bb28a2849'
            '7f0c64cd87b61e894be632f180ae5291e1aa9f1d9d382608f659067eeeda7146'
            'ef2ae12a4d6ac7a52d38bb305818b26c830ae42d14468e4b1913157d998b2137'
            '294756995c1d528f9b5d4b64559edfee151ce0a06bd863a2cafce58a82ce53fd'
            'b81c6ae4eaa5fba28b5827cf11bc12bd52bddc19018c23d4b193346291e01b73'
            'de20db3d23020a6e734d87e168c1661a904a88aa32f68d5ef17984753e8eacc8'
            'd0a1d4309bbe999e2af0ee37361714cb94bb6123145a6cacc2c1482e87ad8e4e'
            '2f66a5073f17e8cad35aab8c545b34bb3a2263aa693e138b6af6724caeda6d70'
            '715cb8862753854b2d9256e0b70003e2d1f57083d83eaeaf5a095fc72b8a4e26'
            'd4b6d171f3fd878b7a21043824c0477235c7acb6a73115a337295724ff8b0d1c'
            'de631ab199a6fe83b3f695350bffaad067a2f95fc2ba9c8fe57dc85665d3653c'
            '614a86cb22d3785d8099760c00f3981908c9a97b65b280e7350ee5dd1a0967bd')
validpgpkeys=('B6C8F98282B944E3B0D5C2530FC3042E345AD05D'  # Hans Wennborg, Google.
              '474E22316ABF4785A88C6E8EA2C794A986419D8A'  # Tom Stellard
              'D574BD5D1D0E98895E3BF90044F2485E45D59042') # Tobias Hieta
noextract=(clang-${pkgver}.src.tar.xz)

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

revert_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Reverting ${_patch}"
    patch -Rbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}"
  plain "Extracting clang-${pkgver}.src.tar.xz due to symlink(s) without pre-existing target(s)"
  tar -xJf ${srcdir}/clang-${pkgver}.src.tar.xz -C ${srcdir} || true

  # Rename Directories
  for pkg in llvm clang clang-tools-extra compiler-rt lld cmake third-party; do
    mv ${pkg}-$pkgver.src ${pkg}
  done

  # https://github.com/llvm/llvm-project/issues/63132
  apply_patch_with_msg \
    ab8d4f5a122fde5740f8c084c8165f51a26c93c7.patch

  # Patch llvm
  cd "${srcdir}/llvm"
  apply_patch_with_msg \
    "0001-Fix-GetHostTriple-for-mingw-w64-in-msys.patch" \
    "0002-Revert-CMake-try-creating-symlink-first-on-windows.patch" \
    "0005-Fix-Any-linker-error-with-multiple-compilers.patch"

  # upstream commits 9080f619461f 8deeaef0291f 6540157fe389 fb19fa2f3dfd
  apply_patch_with_msg \
    "0006-COFF-Remove-misleading-and-unclear-comments.-NFC.patch" \
    "0007-llvm-dlltool-Clarify-parameters-simplify-ArgList-usa.patch" \
    "0008-llvm-dlltool-Ignore-the-temp-prefix-option.patch" \
    "0009-llvm-dlltool-Implement-the-no-leading-underscore-opt.patch"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0003-add-pthread-as-system-lib-for-mingw.patch" \
      "0004-enable-emutls-for-mingw.patch"
  fi

  # Patch clang
  cd "${srcdir}/clang"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0101-link-pthread-with-mingw.patch"
  fi
  # https://reviews.llvm.org/D143592
  apply_patch_with_msg \
    "0102-Rename-flang-new-flang-experimental-exec-to-flang.patch"

  # Patch lld
  cd "${srcdir}/lld"

  apply_patch_with_msg \
    "0303-ignore-new-bfd-options.patch"

  # Patch clang-tools-extra
  cd "${srcdir}/clang-tools-extra"
}

build() {
  cd "${srcdir}"

  case "${CARCH}" in
    i?86|armv7)
      # lld needs all the address space it can get.
      LDFLAGS+=" -Wl,--large-address-aware"
      ;;
  esac

  local -a platform_config
  local -a common_cmake_args

  if check_option "debug" "y"; then
    common_cmake_args+=(-DCMAKE_BUILD_TYPE=Debug)
    VERBOSE="VERBOSE=1"
  else
    common_cmake_args+=(-DCMAKE_BUILD_TYPE=Release)
  fi
  common_cmake_args+=(-Wno-dev
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX}
    -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib
    -DLLVM_HOST_TRIPLE="${CARCH}-w64-windows-gnu"
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe
    -DPython3_FIND_REGISTRY=NEVER
    -DPython3_ROOT_DIR=${MINGW_PREFIX})

  # Include location of libffi headers in CPPFLAGS
  FFI_INCLUDE_DIR="$(pkg-config --cflags libffi)"
  FFI_INCLUDE_DIR=$(echo $FFI_INCLUDE_DIR | sed 's|-I||g')

  if [ "${_compiler}" == "clang" ]; then
    export CC='clang'
    export CXX='clang++'
  fi

  if (( _clangprefix )); then
    # A bit hacky but it works
    local _clang_links="clang++;clang-cpp;as;c++;cc;cpp;${MINGW_CHOST}-cc;${MINGW_CHOST}-c++;${MINGW_CHOST}-clang;${MINGW_CHOST}-clang++"

    platform_config+=(-DCLANG_DEFAULT_RTLIB=compiler-rt
      -DCOMPILER_RT_USE_BUILTINS_LIBRARY=ON
      -DCLANG_DEFAULT_UNWINDLIB=libunwind
      -DCLANG_DEFAULT_CXX_STDLIB=libc++
      -DLLVM_ENABLE_LIBCXX=ON
      -DCLANG_DEFAULT_LINKER=lld
      -DLLVM_ENABLE_LLD=ON
      -DCLANG_LINKS_TO_CREATE="${_clang_links}"
      -DLLVM_INSTALL_BINUTILS_SYMLINKS=ON)
  fi

  local _projects="clang;clang-tools-extra;compiler-rt;lld"

  case "${CARCH}" in
    x86_64|i?86)
      platform_config+=(-DCOMPILER_RT_BUILD_SANITIZERS=$( (( _clangprefix )) && echo "ON" || echo "OFF"))
      ;;
    armv7|aarch64)
      platform_config+=(-DCOMPILER_RT_BUILD_MEMPROF=OFF
        -DCOMPILER_RT_BUILD_SANITIZERS=OFF
        -DCOMPILER_RT_BUILD_XRAY=OFF)
      ;;
  esac

  # List of targets to build in CMake style
  # For more info see: https://github.com/msys2/MINGW-packages/discussions/9765
  if [ "${_compiler}" == "clang" ]; then
    platform_config+=(-DLLVM_TARGETS_TO_BUILD="all")
  else
    platform_config+=(-DLLVM_TARGETS_TO_BUILD="AArch64;AMDGPU;ARM;AVR;BPF;Mips;MSP430;NVPTX;RISCV;WebAssembly;X86")
  fi

  mkdir build-${MSYSTEM} && cd build-${MSYSTEM}

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -GNinja \
    -DFFI_INCLUDE_DIR="${FFI_INCLUDE_DIR}" \
    -DLIBCLANG_BUILD_STATIC=ON \
    -DLLD_DEFAULT_LD_LLD_IS_MINGW=ON \
    -DLLVM_BUILD_LLVM_DYLIB=ON \
    -DLLVM_BUILD_STATIC=OFF \
    -DLLVM_ENABLE_ASSERTIONS=OFF \
    -DLLVM_ENABLE_FFI=ON \
    -DLLVM_ENABLE_PROJECTS="${_projects}" \
    -DLLVM_ENABLE_SPHINX=ON \
    -DLLVM_ENABLE_THREADS=ON \
    -DLLVM_ENABLE_RTTI=ON \
    -DLLVM_INCLUDE_EXAMPLES=OFF \
    -DLLVM_INCLUDE_BENCHMARKS=OFF \
    -DLLVM_INCLUDE_TESTS=OFF \
    -DLLVM_INSTALL_UTILS=ON \
    -DLLVM_LINK_LLVM_DYLIB=ON \
    "${common_cmake_args[@]}" \
    "${platform_config[@]}" \
    ../llvm

  ${MINGW_PREFIX}/bin/cmake.exe --build .

  # Disable automatic installation of components that go into subpackages
  # -i.orig to check what has been removed in-case it starts dropping more than it should
  #
  sed -i.orig '/\(clang\|lld\)\/cmake_install.cmake/d' tools/cmake_install.cmake
  sed -i.orig '/\(extra\|scan-build\|scan-build-py\|scan-view\)\/cmake_install.cmake/d' tools/clang/tools/cmake_install.cmake
  sed -i.orig '/compiler-rt\/cmake_install.cmake/d' projects/cmake_install.cmake
}

check() {
 cd "${srcdir}"/build-${MSYSTEM}
 # Remove || true once testcase doesn't cause failures.
#  make check || true
#  make check-clang || true
  ${MINGW_PREFIX}/bin/cmake.exe -DLLVM_INCLUDE_TESTS=ON ../llvm
  ${MINGW_PREFIX}/bin/cmake.exe --build .
  ${MINGW_PREFIX}/bin/cmake.exe --build . -- check-lld || true
}

package_clang() {
  pkgdesc="C language family frontend for LLVM (mingw-w64)"
  url="https://clang.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm=${pkgver}"
           $( ((_clangprefix)) && echo \
             "${MINGW_PACKAGE_PREFIX}-compiler-rt=${pkgver}" \
             "${MINGW_PACKAGE_PREFIX}-crt" \
             "${MINGW_PACKAGE_PREFIX}-headers" \
             "${MINGW_PACKAGE_PREFIX}-lld=${pkgver}" \
             "${MINGW_PACKAGE_PREFIX}-winpthreads" \
             || echo "${MINGW_PACKAGE_PREFIX}-gcc"))
  provides=($( (( _clangprefix )) && echo \
             "${MINGW_PACKAGE_PREFIX}-cc" \
             || true ))

  cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang" --prefix "${pkgdir}${MINGW_PREFIX}"
}

package_clang-analyzer() {
  pkgdesc="A source code analysis framework (mingw-w64)"
  url="https://clang-analyzer.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-clang=${pkgver}"
           "${MINGW_PACKAGE_PREFIX}-python")

  local _analyzer
  for _analyzer in scan-build scan-build-py scan-view; do
    DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang/tools/${_analyzer}"
  done

  # Compile Python scripts
  ${MINGW_PREFIX}/bin/python -m compileall "${pkgdir}"${MINGW_PREFIX}/lib/libscanbuild
  ${MINGW_PREFIX}/bin/python -O -m compileall "${pkgdir}"${MINGW_PREFIX}/lib/libscanbuild

  install -Dm644 "${srcdir}/clang/LICENSE.TXT" "${pkgdir}"${MINGW_PREFIX}/share/licenses/clang-analyzer/LICENSE
}

package_clang-tools-extra() {
  pkgdesc="Extra tools built using Clang's tooling APIs (mingw-w64)"
  url="https://clang.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-clang=${pkgver}")

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang/tools/extra"
}

package_compiler-rt() {
  pkgdesc="Runtime libraries for Clang and LLVM (mingw-w64)"
  url="https://compiler-rt.llvm.org/"
  depends=($( (( _clangprefix )) || echo "${MINGW_PACKAGE_PREFIX}-gcc-libs"))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/projects/compiler-rt"
  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin/"
  find "${pkgdir}${MINGW_PREFIX}/lib/clang/${_version%.[0-9].*}/lib/windows/" \
    -name '*.dll' -exec mv '{}' "${pkgdir}${MINGW_PREFIX}/bin/" \;
  # remove bin dir we created if it is still empty
  rmdir "${pkgdir}${MINGW_PREFIX}/bin/" 2>/dev/null || true
}

package_gcc-compat() {
  pkgdesc="GCC compatibility aliases for Clang (mingw-w64)"
  url="https://clang.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-clang=${pkgver}-${pkgrel}")
  provides=("${MINGW_PACKAGE_PREFIX}-gcc")
  conflicts=("${MINGW_PACKAGE_PREFIX}-gcc")

  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin"
  local _alias
  for _alias in gcc g++ ${MINGW_CHOST}-gcc ${MINGW_CHOST}-g++; do
    cp -f "${srcdir}/build-${MSYSTEM}/bin/clang.exe" "${pkgdir}${MINGW_PREFIX}/bin/${_alias}.exe"
  done
}

package_lld() {
  pkgdesc="Linker tools for LLVM (mingw-w64)"
  url="https://lld.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm=${pkgver}")
  provides=($( (( _clangprefix )) && echo \
             "${MINGW_PACKAGE_PREFIX}-binutils" \
             || true))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/lld"
  if (( _clangprefix )); then
    install -Dm755 "${pkgdir}${MINGW_PREFIX}/bin/lld.exe" "${pkgdir}${MINGW_PREFIX}/bin/ld.exe"
  fi
}

package_llvm() {
  pkgdesc="Low Level Virtual Machine (mingw-w64)"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm-libs")

  cd "${srcdir}"/llvm

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}"

  install -Dm644 "${srcdir}/llvm/LICENSE.TXT" "${pkgdir}${MINGW_PREFIX}/share/licenses/llvm/LICENSE"

  # Runtime libraries
  rm -rf "${srcdir}/llvm-libs"
  mkdir -p "${srcdir}/llvm-libs/${MINGW_PREFIX}/bin"
  mv -f "${pkgdir}${MINGW_PREFIX}"/bin/lib{LLVM-*,LTO,Remarks}.dll "${srcdir}/llvm-libs/${MINGW_PREFIX}/bin"

  # Provide gcov on CLANG*
  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    cp "${pkgdir}"${MINGW_PREFIX}/bin/llvm-cov.exe "${pkgdir}"${MINGW_PREFIX}/bin/gcov.exe
  fi

  # Install CMake stuff
  install -d "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/{modules,platforms}
  install -Dm644 "${srcdir}"/llvm/cmake/modules/*.cmake "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/modules/
  install -Dm644 "${srcdir}"/llvm/cmake/platforms/*.cmake "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/platforms/

  # fix cmake files.
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  sed -e "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i ${pkgdir}/${MINGW_PREFIX}/lib/cmake/llvm/LLVMExports.cmake
}

package_llvm-libs() {
  pkgdesc="Low Level Virtual Machine Runtime Libraries (mingw-w64)"
  depends=("${MINGW_PACKAGE_PREFIX}-libffi"
           "${MINGW_PACKAGE_PREFIX}-gcc-libs"
           "${MINGW_PACKAGE_PREFIX}-zlib"
           "${MINGW_PACKAGE_PREFIX}-libxml2"
           "${MINGW_PACKAGE_PREFIX}-zstd")
  conflicts=("${MINGW_PACKAGE_PREFIX}-llvm<16.0.2-2")

  cp -r "${srcdir}/llvm-libs/${MINGW_PREFIX}" "${pkgdir}${MINGW_PREFIX}"

  install -Dm644 "${srcdir}/llvm/LICENSE.TXT" "${pkgdir}${MINGW_PREFIX}/share/licenses/llvm-libs/LICENSE"
}

# template start; name=mingw-w64-splitpkg-wrappers; version=1.0;
# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
# template end;
